package com.homework;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 作业1
 *服务端
 */
public class Hserver01 {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket=new ServerSocket(6666);
        //等待连接
        Socket socket=serverSocket.accept();
        //读取数据
        BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
        BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        String anser=bufferedReader.readLine();
        if(anser.equals("name")){
            bufferedWriter.write("nova");
            bufferedWriter.newLine();
            bufferedWriter.flush();
        }
        else if(anser.equals("hobby")){
            bufferedWriter.write("编写java程序");
            bufferedWriter.newLine();
            bufferedWriter.flush();
        }
        else{
            bufferedWriter.write("你说哪样");
            bufferedWriter.newLine();
            bufferedWriter.flush();
        }

        //关闭流
        serverSocket.close();
        socket.close();
        bufferedWriter.close();
        bufferedReader.close();

    }
    public static void error() throws IOException {
        ServerSocket serverSocket=new ServerSocket(6666);
        //等待连接
        Socket socket=serverSocket.accept();
        //读取数据
        String path="D:\\javacode\\javacode\\J2024_11_21\\hello.txt";
        BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
        BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        int len=0;
        char[] buf=new char[1024];
        while((len=bufferedReader.read(buf))!=-1){
            String message=new String(buf,0,len);
            if(message.equals("name")){//回复nova
                String name="nova";
                bufferedWriter.write(name,0,name.length());
                bufferedWriter.newLine();
                bufferedWriter.flush();
                //        socket.shutdownOutput();
            }
            else if(message.equals("hobby")){//回复"编写java程序"
                String hobby="编写java程序";
                bufferedWriter.write(hobby,0,hobby.length());
                bufferedWriter.newLine();
                bufferedWriter.flush();
                //     socket.shutdownOutput();
            }
            else{
                String other="你说啥呢?";
                bufferedWriter.write(other,0,other.length());
                bufferedWriter.newLine();

                bufferedWriter.flush();
                //        socket.shutdownOutput();
            }
        }

        //关闭流
        serverSocket.close();
        socket.close();
        bufferedWriter.close();
        bufferedReader.close();

    }
}
